package com.bookrecomm.crawler.util;

import lombok.extern.slf4j.Slf4j;
import java.sql.*;
import java.util.Properties;
import java.io.InputStream;

/**
 * 数据库连接工具类
 * 负责创建和管理数据库连接
 */
@Slf4j
public class DatabaseUtil {
    private static final String CONFIG_FILE = "database.properties";
    private static String url;
    private static String username;
    private static String password;
    private static String driverClass;
    
    // 静态代码块，加载配置文件
    static {
        try {
            Properties prop = new Properties();
            InputStream inputStream = DatabaseUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE);
            prop.load(inputStream);
            
            url = prop.getProperty("jdbc.url");
            username = prop.getProperty("jdbc.username");
            password = prop.getProperty("jdbc.password");
            driverClass = prop.getProperty("jdbc.driverClass");
            
            // 加载驱动
            Class.forName(driverClass);
            log.info("数据库驱动加载成功");
        } catch (Exception e) {
            log.error("加载数据库配置失败", e);
        }
    }
    
    /**
     * 获取数据库连接
     * @return Connection 数据库连接对象
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            log.error("获取数据库连接失败", e);
        }
        return conn;
    }
    
    /**
     * 关闭数据库连接资源
     * @param conn 数据库连接
     * @param stmt Statement对象
     * @param rs ResultSet对象
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            log.error("关闭ResultSet失败", e);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                log.error("关闭Statement失败", e);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    log.error("关闭Connection失败", e);
                }
            }
        }
    }
    
    /**
     * 提交事务
     * @param conn 数据库连接
     */
    public static void commit(Connection conn) {
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException e) {
                log.error("提交事务失败", e);
            }
        }
    }
    
    /**
     * 回滚事务
     * @param conn 数据库连接
     */
    public static void rollback(Connection conn) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                log.error("回滚事务失败", e);
            }
        }
    }
}
